using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public enum StateType
{
    Idle,Patrol,Chase,React,Attack
}

[Serializable]
public class Parameter{
    public float health;
    public float moveSpeed;
    public float ChaseSpeed;
    public float IdleTime;

    public Transform[] patrolPoints;
    public Transform[] chasePoints;

    public Transform target;


    public LayerMask attackLayer;
    public Transform attackPostion;
    public float attackArea;
    public Animator animator;  


    
}

public class FSM : MonoBehaviour
{
    public Parameter parameter;
    public IState currentState;

    private Dictionary<StateType,IState> states = new Dictionary<StateType, IState>();

    private void Start() {
        states.Add(StateType.Idle,new IdleState(this));
        states.Add(StateType.Patrol,new PatrolState(this));
        states.Add(StateType.Chase,new ChaseState(this));
        states.Add(StateType.React,new ReactState(this));
        states.Add(StateType.Attack,new AttackState(this));

        TransitionState(StateType.Idle);
    }

    private void Update() {
        currentState.OnUpdate();
    }

    public void TransitionState(StateType type)
    {
        if(currentState != null)
            currentState.OnExit();
        currentState = states[type];
        currentState.OnEnter();
    }

    public void FlipTo(Transform traget){
        if(traget != null)
        {
            if(transform.localPosition.x > traget.position.x)
            {
                transform.localScale = new Vector3(-1,1,1);
            }
            else if(transform.position.x < traget.position.x)
            {
                transform.localScale = new Vector3(1,1,1);
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D other) {
        if(other.CompareTag("Player"))
            parameter.target = other.transform;
    }

    private void OnTriggerExit2D(Collider2D other) {
        if(other.CompareTag("Player"))
            parameter.target = null;
    }

    private void OnDrawGizmos() {
        Gizmos.DrawWireSphere(parameter.attackPostion.position,parameter.attackArea);
    }
}
